/**
 * 组织机构选择器
 */
import React from 'react';
import { Spin, TreeSelect } from 'antd';
import { useRequest } from '@/hooks';
import { fetchOrg } from '../service';
import styles from './Organization.less';

const getTreeData = (
    data = [],
    fieldsName = {
        value: 'organizationCode',
        title: 'organizationName',
        orgTitle: 'orgTitle'
    },
    disabledKeys = [],
    orgTitle = ''
) =>
    data?.map(item => ({
        ...item,
        orgTitle: `${orgTitle}${orgTitle ? '/' : ''}${item.organizationName}`,
        value: item[fieldsName.value],
        title: item[fieldsName.title],
        key: item[fieldsName.value],
        disabled: disabledKeys.includes(item[fieldsName.value]),
        children: item.children
            ? getTreeData(
                  item.children,
                  fieldsName,
                  disabledKeys,
                  `${orgTitle}${orgTitle ? '/' : ''}${item.organizationName}`
              )
            : item.children
    }));

const Organization = React.forwardRef(({ value, onChange, requestParams, style, disabledKeys, ...rest }, ref) => {
    const { data, loading } = useRequest(() =>
        fetchOrg({
            organizationPermissions: 1,
            showTreeFlag: 1,
            ...requestParams
        })
    );

    const treeData = React.useMemo(() => {
        const finalData = Array.isArray(data?.data) ? data?.data : [];
        return getTreeData(finalData, undefined, disabledKeys);
    }, [data, disabledKeys]);

    const finalValue = value === '' ? undefined : value;

    return (
        <Spin spinning={loading}>
            <TreeSelect
                ref={ref}
                value={finalValue}
                onChange={onChange}
                treeData={treeData}
                placeholder="请选择组织机构"
                allowClear
                showSearch
                treeNodeFilterProp="title"
                treeDefaultExpandAll
                style={{ width: 170, ...style }}
                dropdownMatchSelectWidth
                dropdownClassName={styles.orgName}
                dropdownStyle={{ maxHeight: 250, minWidth: 400, overflowY: 'visible', overflowX: 'hidden' }}
                getPopupContainer={trigger => trigger.parentNode}
                {...rest}
            />
        </Spin>
    );
});

export default Organization;
